import 'dart:async';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/pay/my_coupon.dart';
import 'package:ball_lion/entity/pay/usable_coupon.dart';
import 'package:ball_lion/server/api/other_api.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/base/wqs_button.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';

class CouponBottomSheet extends StatefulWidget {
  const CouponBottomSheet({super.key, required this.coupons, this.selected});

  final List<UsableCouponEntity> coupons;
  final UsableCouponEntity? selected;

  @override
  State<CouponBottomSheet> createState() => _CouponBottomSheetState();
}

class _CouponBottomSheetState extends State<CouponBottomSheet> {
  List<UsableCouponEntity> get coupons => widget.coupons;
  UsableCouponEntity? get selected => widget.selected;
  String tip = "";

  @override
  void initState() {
    getTip();
    super.initState();
  }

  Future getTip() async {
    var tips = await OtherApi.getAppList("app_res_tips");
    tip = tips
            ?.firstWhere((element) => element.button == "use_coupon_tip")
            .content ??
        "";
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 461,
      clipBehavior: Clip.hardEdge,
      decoration: const BoxDecoration(
          color: Colours.greyF7,
          borderRadius: BorderRadius.vertical(top: Radius.circular(10))),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            height: 56.5,
            color: Colors.white,
            padding: const EdgeInsets.symmetric(horizontal: 12),
            child: Row(
              children: [
                Expanded(
                    child: Row(
                  children: [
                    Image.asset(
                      width: 24,
                      Utils.getImgPath("arrow_back.png"),
                    ).tap(() {
                      Get.back();
                    })
                  ],
                )),
                QsText("选择优惠券"),
                Expanded(
                    child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    QsButton(
                      onPressed: () {
                        if (tip.hasValue) {
                          Get.dialog(QsDialog.single("优惠券使用说明",
                              content: tip, confirmText: "我知道了"));
                        }
                      },
                      text: "使用说明",
                      foregroundColor: Colours.grey666666,
                      textStyle: const TextStyle(
                          fontSize: 14, fontWeight: FontWeight.w400),
                    )
                  ],
                ))
              ],
            ),
          ),
          coupons.isEmpty
              ? const Expanded(
                  child: Center(
                  child: NoDataWidget(tip: "无可用优惠券"),
                ))
              : Expanded(
                  child: ListView.builder(
                  padding: const EdgeInsets.fromLTRB(16, 20, 16, 12),
                  itemCount: coupons.length,
                  itemBuilder: (context, index) {
                    final entity = coupons[index];
                    bool isEnd = index == coupons.length - 1;
                    return MyCouponCardWidget(
                            selectable: true,
                            selected: entity.id == selected?.id,
                            use1Coupon: entity)
                        .marginOnly(bottom: isEnd ? 0 : 10)
                        .tap(() {
                      if (entity.canUse == 1) {
                        Get.back(result: entity);
                      }
                    });
                  },
                )),
          const SizedBox(height: 10),
          Container(
            alignment: Alignment.center,
            margin: const EdgeInsets.symmetric(horizontal: 16),
            height: 44,
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(4)),
            child: QsText("不使用优惠券"),
          ).tap(() {
            log("不使用优惠券");
            Get.back(result: false);
          }),
          const SizedBox(height: 20)
        ],
      ),
    );
  }
}

class DashSeparator extends StatelessWidget {
  const DashSeparator({Key? key, this.height = 1, this.color = Colors.black})
      : super(key: key);
  final double height;
  final Color color;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        final boxWidth = constraints.constrainWidth();
        const dashWidth = 8.0;
        final dashHeight = height;
        final dashCount = (boxWidth / (2 * dashWidth)).floor();
        return Flex(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          direction: Axis.horizontal,
          children: List.generate(dashCount, (_) {
            return SizedBox(
              width: dashWidth,
              height: dashHeight,
              child: DecoratedBox(
                decoration: BoxDecoration(color: color),
              ),
            );
          }),
        );
      },
    );
  }
}

enum MyDiscountUselessType {
  none,
  notStart,
  used,
  expired,
  notfit,
}

extension MyCouponEntityEx1 on MyCouponEntity {
  MyDiscountUselessType? get uselessType => {
        0: MyDiscountUselessType.none,
        -1: MyDiscountUselessType.notStart,
        1: MyDiscountUselessType.used,
        2: MyDiscountUselessType.expired,
      }[status];
}

class MyCouponCardWidget extends StatefulWidget {
  const MyCouponCardWidget(
      {super.key,
      this.selectable = false,
      this.selected = false,
      this.toUse = true,
      this.myCoupon,
      this.use1Coupon});

  final bool selectable;
  final bool selected;
  final bool toUse;
  final MyCouponEntity? myCoupon;
  final UsableCouponEntity? use1Coupon;

  @override
  State<MyCouponCardWidget> createState() => _MyCouponCardWidgetState();
}

class _MyCouponCardWidgetState extends State<MyCouponCardWidget> {
  MyCouponEntity? get myCoupon => widget.myCoupon;
  UsableCouponEntity? get u1coupon => widget.use1Coupon;

  MyDiscountUselessType? get uselessType =>
      myCoupon?.uselessType ??
      (u1coupon?.canUse == 1 ? MyDiscountUselessType.none : null);
  bool get enable =>
      uselessType == MyDiscountUselessType.none ||
      uselessType == MyDiscountUselessType.notStart;
  bool get toUse => widget.toUse && (widget.myCoupon?.useUrl != null);
  bool get selectable => widget.selectable;
  bool get selected => widget.selected;
  String get title => widget.myCoupon?.name ?? u1coupon?.name ?? "";
  String get bottomDescribe =>
      widget.myCoupon?.remark ?? u1coupon?.remark ?? "";
  String get condition => myCoupon?.condition ?? u1coupon?.condition ?? "";
  String get typeUpper => myCoupon?.typeUpper ?? u1coupon?.typeUpper ?? "";
  String get typeLower => myCoupon?.typeLower ?? u1coupon?.typeLower ?? "";
  String get limit => myCoupon?.maxLimit ?? "";
  // double get discountZhe => 8;
  late DateTime startTime;
  late DateTime endTime;

  Timer? t;

  @override
  void initState() {
    super.initState();
    t = Timer.periodic(const Duration(seconds: 1), (timer) {
      update();
    });
    startTime =
        DateTime.tryParse(myCoupon?.startTime ?? u1coupon?.startTime ?? "") ??
            DateTime.now();
    endTime = DateTime.tryParse(myCoupon?.endTime ?? u1coupon?.endTime ?? "") ??
        DateTime.now();
  }

  @override
  void dispose() {
    t?.cancel();
    super.dispose();
  }

  Widget _timeDesc(Color? disableColor) {
    Widget text = QsText("");
    final isUseless = (uselessType == MyDiscountUselessType.expired ||
        uselessType == MyDiscountUselessType.used);
    final tStyle =
        TextStyle(fontSize: 12, color: disableColor ?? Colours.grey66);
    final now = DateTime.now();
    if (isUseless) {
      text = QsText.style(
        "有效期至${endTime.formatedString("yyyy.MM.dd")}",
        style: tStyle,
      );
    } else if (startTime.difference(now).inSeconds > 0) {
      String msg = "";
      final dif = startTime.difference(now);
      final days = dif.inDays;
      final hours = dif.inHours - dif.inDays * 24;
      final minutes = dif.inMinutes - dif.inHours * 60;
      final seconds = dif.inSeconds - dif.inMinutes * 60;
      final nums = [days, hours, minutes, seconds];
      final names = ["天", "小时", "分钟", "秒"];

      var valid = false;
      for (var i = 0; i < nums.length; i++) {
        if (!valid) {
          valid = nums[i] > 0;
        }
        if (valid) {
          final num = nums[i];
          msg += "${"00$num".lastString(2)}${names[i]}";
        }
      }
      msg += "后";

      text = Text.rich(TextSpan(style: tStyle, children: [
        const TextSpan(text: "待生效", style: TextStyle(color: Color(0xFF2766D6))),
        TextSpan(text: msg)
      ]));
    } else if (endTime.difference(now).inDays < 1) {
      final expDur = endTime.difference(DateTime.now());
      final hours = expDur.inHours;
      final minutes = expDur.inMinutes - expDur.inHours * 60;
      final seconds = expDur.inSeconds - expDur.inMinutes * 60;
      text = Text.rich(TextSpan(
          style: const TextStyle(fontSize: 12, color: Colours.grey666666),
          children: [
            TextSpan(
                text: "仅剩 ",
                style: TextStyle(color: disableColor ?? Colours.grey66)),
            TextSpan(
                text:
                    "${"0$hours".lastString(2)}:${"0$minutes".lastString(2)}:${"0$seconds".lastString(2)}",
                style: TextStyle(color: disableColor ?? Colours.main))
          ]));
    } else {
      text = QsText.style("有效期至${endTime.formatedString("yyyy.MM.dd")}",
          style: tStyle);
    }

    return Container(
      child: text,
    );
  }

  @override
  Widget build(BuildContext context) {
    final disableColor = enable ? null : Colours.grey99;
    final con = Container(
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(8)),
      padding: const EdgeInsets.symmetric(horizontal: 12),
      child: Column(
        children: [
          SizedBox(
            height: 82.5,
            child: Column(
              children: [
                Expanded(
                  flex: 7,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      QsText(
                        title,
                        fontSize: 16,
                        color: disableColor ?? Colours.grey66,
                        fontWeight: FontWeight.w600,
                      ).marginOnly(bottom: 5),
                      const Spacer(),
                      Text.rich(TextSpan(children: [
                        TextSpan(
                            text: "$typeUpper",
                            style: TextStyle(
                                color: disableColor ?? Colours.main,
                                fontSize: 30)),
                        TextSpan(
                            text: typeLower,
                            style: TextStyle(
                                fontSize: 12,
                                color: disableColor ?? Colours.main)),
                        // TextSpan(text: limit,style: TextStyle(fontSize: 12,color: disableColor ?? Colours.blue2766D6)),
                      ])),
                      if (selectable)
                        Container(
                            alignment: Alignment.bottomRight,
                            width: 34,
                            child: Image.asset(
                              Utils.getImgPath(
                                  selected ? "check.png" : "uncheck.png"),
                              width: 20,
                              height: 20,
                            ).marginOnly(bottom: 5))
                    ],
                  ),
                ),
                Expanded(
                  flex: 5,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _timeDesc(disableColor),
                      const Spacer(),
                      QsText(
                        condition.changeUnit,
                        color: disableColor ?? Colours.main,
                        fontSize: 12,
                      ),
                      if (selectable)
                        const SizedBox(
                          width: 34,
                        )
                    ],
                  ),
                )
              ],
            ),
          ),
          const DashSeparator(color: Colours.greyEE),
          Container(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: Container(
                    padding: const EdgeInsets.symmetric(vertical: 8),
                    alignment: Alignment.centerLeft,
                    constraints: const BoxConstraints(minHeight: 40),
                    child: QsText(
                      bottomDescribe.changeUnit,
                      fontSize: 12,
                      color: disableColor ?? Colours.grey66,
                    ),
                  ),
                ),
                Container(
                  padding: const EdgeInsets.only(left: 20),
                  height: 40,
                  alignment: Alignment.center,
                  child: !toUse
                      ? null
                      : QsButton(
                          onPressed: () {
                            if (uselessType == MyDiscountUselessType.none) {
                              Utils.doJump(myCoupon?.useUrl ?? "");
                            }
                          },
                          foregroundColor: Colors.white,
                          backgroundColor: Colours.main.withOpacity(
                              uselessType == MyDiscountUselessType.notStart
                                  ? 0.5
                                  : 1),
                          borderRadius: 4,
                          height: 24,
                          width: 56,
                          textStyle: const TextStyle(
                              fontSize: 12, fontWeight: FontWeight.w400),
                          text: "去使用"),
                )
              ],
            ),
          )
        ],
      ),
    );
    String? imgPath;
    if (uselessType == MyDiscountUselessType.used) {
      imgPath = "my_discount_used.png";
    } else if (uselessType == MyDiscountUselessType.expired) {
      imgPath = "my_discount_expired.png";
    }

    return Stack(
      children: [
        con,
        if (imgPath != null)
          Positioned(
            right: 0,
            bottom: 0,
            child: Image.asset(
              Utils.getImgPath(imgPath),
              width: 60,
            ),
          )
      ],
    );
  }
}
